package com.xmu.prcs.dao.impl;

import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;

import com.xmu.prcs.dao.UserDao;
import com.xmu.prcs.entity.Plant;
import com.xmu.prcs.entity.User;

/**
 * 
 * @author frequent
 * @version 1.0,2012-3-20
 *
 */
public class UserDaoImpl extends GenericDaoImpl<User> implements UserDao{

	public UserDaoImpl() {
		super(User.class);
	}

	public List<User> findByProperty(String property, Object param) {
		
		List<User> list = null;
		try{
//			list =this.find(query, param);
			String sql = "from User as u where u." + property + " = ?";
			list = this.getHibernateTemplate().find(sql, param);
		}catch(Exception e){
			e.printStackTrace();
			return null;
		}catch(Throwable t){
			t.printStackTrace();
			return null;
		}
		return list;
	}

	public List<User> find4page(int begin, int size, String name) {
		String sql = "select * from user as u";
		if(name != null && !name.equals("")){
			sql += " where u.username like '%" + name + "%'";
		}
		sql += " order by u.registertime desc";
		Query query = getHibernateTemplate().getSessionFactory()
				.getCurrentSession().createSQLQuery(sql).addEntity(User.class);
		query.setFirstResult(begin);
		query.setMaxResults(size);
		
		return query.list();
	}

	public int countUsers(String name) {
		String sql = "select count(1) from user";
		if(name != null && !name.equals("")){
			sql += " where user.username like '%" + name + "%'";
		}
		Session session = getHibernateTemplate().getSessionFactory().getCurrentSession();
		Query query = session.createSQLQuery(sql);
		int size;
		if(query.uniqueResult() == null){
			size = 0;
		}
		size = Integer.parseInt((query.uniqueResult().toString()));
		System.out.println("size:" + size);
		return size;
	}

}
